#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SurveyAnalyzer Web应用启动脚本

这个脚本用于启动SurveyAnalyzer的Web界面。
"""

import os
import sys
import argparse
import logging
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
sys.path.insert(0, str(project_root / 'src'))

try:
    from src.web.app import create_app
    from src.core.config import Config
    from src.utils.logger import get_logger
except ImportError as e:
    print(f"导入错误: {e}")
    print("请确保已安装所有依赖包: pip install -r requirements.txt")
    sys.exit(1)

def setup_environment():
    """
    设置环境变量和配置
    """
    # 设置环境变量
    os.environ.setdefault('FLASK_APP', 'src.web.app')
    os.environ.setdefault('FLASK_ENV', 'development')
    
    # 创建必要的目录
    directories = [
        'data',
        'uploads',
        'exports',
        'logs',
        'temp'
    ]
    
    for directory in directories:
        dir_path = project_root / directory
        dir_path.mkdir(exist_ok=True)
        print(f"✓ 目录已创建: {dir_path}")

def check_dependencies():
    """
    检查依赖包是否已安装
    """
    required_packages = [
        ('flask', 'flask'),
        ('pandas', 'pandas'),
        ('numpy', 'numpy'),
        ('scikit-learn', 'sklearn'),
        ('matplotlib', 'matplotlib'),
        ('seaborn', 'seaborn'),
        ('plotly', 'plotly')
    ]
    
    missing_packages = []
    
    for display_name, import_name in required_packages:
        try:
            __import__(import_name)
            print(f"✓ {display_name} 已安装")
        except ImportError:
            missing_packages.append(display_name)
            print(f"✗ {display_name} 未安装")
    
    if missing_packages:
        print(f"\n缺少以下依赖包: {', '.join(missing_packages)}")
        print("请运行: pip install -r requirements.txt")
        return False
    
    return True

def main():
    """
    主函数
    """
    parser = argparse.ArgumentParser(description='SurveyAnalyzer Web应用启动器')
    parser.add_argument('--host', default='127.0.0.1', help='服务器主机地址 (默认: 127.0.0.1)')
    parser.add_argument('--port', type=int, default=5000, help='服务器端口 (默认: 5000)')
    parser.add_argument('--debug', action='store_true', help='启用调试模式')
    parser.add_argument('--no-check', action='store_true', help='跳过依赖检查')
    parser.add_argument('--config', help='配置文件路径')
    
    args = parser.parse_args()
    
    print("="*60)
    print("    SurveyAnalyzer Web应用启动器 v2.0.0")
    print("    专业的问卷调查数据分析平台")
    print("="*60)
    print()
    
    # 检查依赖
    if not args.no_check:
        print("检查依赖包...")
        if not check_dependencies():
            sys.exit(1)
        print()
    
    # 设置环境
    print("设置环境...")
    setup_environment()
    print()
    
    # 设置日志
    try:
        logger = get_logger('web_app')
        logger.info("日志系统已初始化")
    except Exception as e:
        print(f"警告: 日志系统初始化失败: {e}")
        logger = logging.getLogger('web_app')
    
    # 加载配置
    try:
        if args.config:
            config = Config.from_file(args.config)
        else:
            config = Config()
        
        logger.info("配置已加载")
    except Exception as e:
        print(f"警告: 配置加载失败: {e}")
        config = None
    
    # 创建Flask应用
    try:
        app = create_app(config)
        logger.info("Flask应用已创建")
    except Exception as e:
        print(f"错误: 创建Flask应用失败: {e}")
        sys.exit(1)
    
    # 显示启动信息
    print(f"启动服务器...")
    print(f"主机: {args.host}")
    print(f"端口: {args.port}")
    print(f"调试模式: {'开启' if args.debug else '关闭'}")
    print(f"访问地址: http://{args.host}:{args.port}")
    print()
    print("按 Ctrl+C 停止服务器")
    print("="*60)
    
    try:
        # 启动服务器
        app.run(
            host=args.host,
            port=args.port,
            debug=args.debug,
            threaded=True
        )
    except KeyboardInterrupt:
        print("\n服务器已停止")
    except Exception as e:
        print(f"\n错误: 服务器启动失败: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()